<?php
/* **************************************************************************
EstateAgent Improved- Joomla Component

File:					mtgcalculator.php
Version: 			1.3.x Improved
Created with: 	QuantaPlus 3.4.3 (http://kdewebdev.org)
						Eclipse 3.1.0 (http://www.eclipse.org)
						on RedHat/Fedora Linux Core4 (http://fedora.redhat.com)
Improved by Manos Orfanoudakis  2007 www.eaimproved.eu	
This file is using parts of the following script:
	
	PHP Mortgage Calculator
    (mortgage_calculator.php)
    Copyright (c) 2002 David Tufts <http://dave.imarc.net>
    All rights reserved.
	
	The PHP Mortgage Calculator tries to figure out a home
    owners mortgage payments, and the breakdown of each monthly
    payment.

    The calculator accepts:
    	Price (cost of home)
        Percentage of Down Payment
        Length of Mortgage
        Annual Interest Rate

	Based on the four items that the user enters, we can figure
    out the down payment, the ammount that the
    buyer needs to finance, and the monthly finance payment.
    The calculator can also break down the monthly payments
    so we know how much goes towards the mortgage's interest,
    the mortgage's principal, the loan's Private Mortgage Insurance
    (if less that 20% was used as a down payment), and an rough
    estimate of the property's residential tax

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    *    Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
    *    Redistributions in binary form must reproduce the above
     copyright notice, this list of conditions and the following
     disclaimer in the documentation and/or other materials
     provided with the distribution.
    *    Neither the name of David Tufts nor the names of its
     contributors may be used to endorse or promote products
     derived from this software without specific prior
     written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
    CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
    BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
mosCommonHTML::loadOverlib();
$mainframe->setPageTitle(_EA_MTGCALC);


// Set Form DEFAULT values
$default_sale_price						= mosGetParam( $_REQUEST, 'price', '');
$default_annual_interest_percent 	= $eaconf->ea_mtg_default_interest_percent;
$default_year_term               			= $eaconf->ea_mtg_default_year_term;
$default_down_percent            		= $eaconf->ea_mtg_default_down_percent;
$default_show_progress           		= $eaconf->ea_mtg_default_show_progress;

// Initialize Variables
$sale_price                   		= 0;
$annual_interest_percent   	= 0;
$year_term                       	= 0;
$down_percent                  	= 0;
$this_year_interest_paid    	= 0;
$this_year_principal_paid   	= 0;
$pmi_pm							= 57;
$form_complete               	= false;
$show_progress                	= false;
$monthly_payment            	= false;
$show_progress                	= false;
$error                           		= false;

	

// Set the USER INPUT values

if (isset($_REQUEST['form_complete'])) {

	$sale_price						= $_REQUEST['sale_price']? $_REQUEST['sale_price'] : $default_sale_price;
	
    $annual_interest_percent   	= mosGetParam( $_REQUEST,'annual_interest_percent', $default_annual_interest_percent);
    $year_term                       	= mosGetParam( $_REQUEST,'year_term', $default_year_term);
    $down_percent                  	= mosGetParam( $_REQUEST,'down_percent', $default_down_percent);
    $show_progress                	= (isset($_REQUEST['show_progress'])) ? $_REQUEST['show_progress'] : false;
	$form_complete                	= $_REQUEST['form_complete'];
}
/* --------------------------------------------------- */

// This function does the actual mortgage calculations
// by plotting a PVIFA (Present Value Interest Factor of Annuity)
// table...
function get_interest_factor($year_term, $monthly_interest_rate) {
	global $base_rate;

    $factor      = 0;
    $base_rate   = 1 + $monthly_interest_rate;
    $denominator = $base_rate;
    for ($i=0; $i < ($year_term * 12); $i++) {
    	$factor += (1 / $denominator);
        $denominator *= $base_rate;
    }
    return $factor;
}

// If the form is complete, we'll start the math
if ($form_complete) {
	// We'll set all the numeric values to JUST
    // numbers - this will delete any dollars signs,
    // commas, spaces, and letters, without invalidating
    // the value of the number
    $sale_price              			= ereg_replace( "[^0-9.]", "", $sale_price);
    $annual_interest_percent 	= eregi_replace("[^0-9.]", "", $annual_interest_percent);
    $year_term               			= eregi_replace("[^0-9.]", "", $year_term);
    $down_percent            		= eregi_replace("[^0-9.]", "", $down_percent);

    if (((float) $year_term <= 0) || ((float) $sale_price <= 0) || ((float) $annual_interest_percent <= 0)) {
    	$error = _EA_MTGERROR1;
    }

    if (!$error) {
    	$month_term              	= $year_term * 12;
        $down_payment          	= $sale_price * ($down_percent / 100);
        $annual_interest_rate   	= $annual_interest_percent / 100;
        $monthly_interest_rate   = $annual_interest_rate / 12;
        $financing_price         	= $sale_price - $down_payment;
        $monthly_factor         	= get_interest_factor($year_term, $monthly_interest_rate);
        $monthly_payment     	= $financing_price / $monthly_factor;
    }
}
else {
 		if (!$sale_price) $sale_price = $default_sale_price;
        if (!$annual_interest_percent) $annual_interest_percent = $default_annual_interest_percent;
        if (!$year_term) $year_term = $default_year_term;
        if (!$down_percent) $down_percent = $default_down_percent;
        if (!$show_progress) $show_progress = $default_show_progress;
}

if ($error) {
	print("<font color=\"red\">" . $error . "</font><br/><br/>\n");
    $form_complete   = false;
}

?>


<form method="get" name="information" action="index2.php">
<input type="hidden" name="option" value="com_estateagent" />
<input type="hidden" name="act" value="mtgcalc" />
<input type="hidden" name="Itemid" value="<?php echo $Itemid?>" />
<input type="hidden" name="form_complete" value="1" />

<table class="contentpaneopen" style="border: solid 1px lightgrey; width:100%">
<tr style="background-color:#cccccc">
	<td class="contentheading" style="text-align:center" colspan="2"><?php echo _EA_MTG_PURCHASE;?>&nbsp;<?php $tip=_EA_MTG_INFO; echo mosToolTip($tip);?></td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
	<td style="width:30%; text-align:right"><?php echo _EA_MTG_SALESPRICE;?></td>
    <td style="width:70%"><input class="inputbox" type="text" size="10" name="sale_price" value="<?php echo $sale_price; ?>"/><?php echo $eaconf->ea_currency;?></td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
	<td style="text-align:right"><?php echo _EA_MTG_PRCNTDOWN;?></td>
    <td><input class="inputbox" type="text" size="3" name="down_percent" value="<?php echo $down_percent; ?>"/>%</td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
	<td style="text-align:right"><?php echo _EA_MTG_LENGTH;?></td>
    <td><input class="inputbox" type="text" size="3" name="year_term" value="<?php echo $year_term; ?>"/><?php echo _EA_MTG_YEARS;?></td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
	<td style="text-align:right"><?php echo _EA_MTG_INTERESTRATE;?></td>
    <td><input class="inputbox" type="text" size="3" name="annual_interest_percent" value="<?php echo $annual_interest_percent; ?>"/>%</td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
	<td style="text-align:right"><?php echo _EA_MTG_EXPLAINCALC;?></td>
    <td><input class="inputbox" type="checkbox" name="show_progress" value="1" <?php if ($show_progress) { print("checked='checked'"); } ?>/><?php echo  _EA_MTG_SHOWCALC;?></td>
</tr>
<tr valign="top" style="background-color:#eeeeee">
    <td>&nbsp;</td>
    <td><input class="button" type="submit" value="<?php echo _EA_MTG_CALCBTN;?>"/><br /></td>
</tr>
<?php
    // If the form has already been calculated, the $down_payment
    // and $monthly_payment variables will be figured out, so we
    // can show them in this table
    if ($form_complete && $monthly_payment) {
?>
        <tr>
			<td colspan="2"><br /></td>
		</tr>
		<tr style="background-color:#cccccc" >
            <td class="contentheading" style="text-align:center" colspan="2"><?php echo _EA_MTG_PAYMENT;?></td>
        </tr>
        <tr valign="top" style="background-color:#eeeeee">
            <td style="text-align:right"><?php echo _EA_MTG_DOWNPAYMENT;?></td>
            <td><b><?php echo $eahelper->valFormat($down_payment) ?></b></td>
        </tr>
        <tr valign="top" style="background-color:#eeeeee">
            <td style="text-align:right"><?php echo _EA_MTG_FINANCED;?></td>
            <td><b><?php echo  $eahelper->valFormat($financing_price) ?></b></td>
        </tr>
        <tr valign="top" style="background-color:#cccccc">
            <td style="text-align:right"><?php echo _EA_MTG_MONTHLYPAYMNT;?></td>
            <td><b><?php echo $eahelper->valFormat($monthly_payment)  ?></b><br/><?php echo _EA_MTG_PMIINTEREST;?></td>
        </tr>
        <?php
            if ($down_percent < 20) {
                $pmi_per_month = $pmi_pm * ($financing_price / 100000);
        ?>
        <tr valign="top" style="background-color:#FFFFCC">
        	<td style="text-align:right">&nbsp;</td>
            <td>
                <br/>
                 <?php echo _EA_MTG_LESSDOWN;?>(<a href="http://www.google.com/search?hl=en&amp;q=private+mortgage+insurance" target="_blank"><?php echo _EA_MTG_PMI;?></a>),&nbsp;<?php echo _EA_MTG_PMI2;?>&nbsp;<?php echo $pmi_pm . " " . $eaconf->ea_currency;?>&nbsp;<?php echo _EA_MTG_PMI3;?><?php echo $eaconf->ea_currency;?>&nbsp;<?php echo _EA_MTG_PMI4;?>&nbsp;<?php echo  $eahelper->valFormat($pmi_per_month);?>&nbsp;<?php echo _EA_MTG_PMI5;?>
            </td>
        </tr>
        <tr valign="top" style="background-color:#FFFF99">
        	<td style="text-align:right"><?php echo _EA_MTG_MONTHLYPAYMNT;?></td>
            <td><b><?php echo  $eahelper->valFormat(($monthly_payment + $pmi_per_month)); ?></b><br/><?php echo _EA_MTG_PMIINTEREST2;?></td>
        </tr>
        <?php
            }
        ?>
        <tr valign="top" style="background-color:#CCCCFF">
        	<td style="text-align:right">&nbsp;</td>
            <td>
                <br/>
                <?php
                    $assessed_price          = ($sale_price * .85);
                    $residential_yearly_tax  = ($assessed_price / 1000) * 14;
                    $residential_monthly_tax = $residential_yearly_tax / 12;

                    if ($pmi_per_month) {
                        $pmi_text = _EA_MTG_PMITXT;
                    }
                ?>
                <?php echo _EA_MTG_TAXES;?>&nbsp;<?php echo  $eahelper->valFormat($assessed_price); ?>. <?php echo _EA_MTG_TAXES2;?>&nbsp;<?php echo  $eahelper->valFormat($residential_yearly_tax); ?>
                <?php echo _EA_MTG_TAXES3;?>&nbsp;<?php echo  $eahelper->valFormat($residential_monthly_tax); ?>&nbsp;<?php echo _EA_MTG_TAXES4;?>
            </td>
        </tr>
        <tr valign="top" style="background-color:#9999FF">
            <td style="text-align:right"><?php echo _EA_MTG_TOTALPAYMNT;?></td>
            <td><b><?php echo  $eahelper->valFormat($monthly_payment + $pmi_per_month + $residential_monthly_tax); ?></b><br/>
			<?php printf(_EA_MTG_PMITEXT, $pmi_text); ?></td>
        </tr>
<?php
    }
?>
</table>
</form>
<?php
    // This prints the calculation progress and
    // the instructions of HOW everything is figured
    // out
    if ($form_complete && $show_progress) {
        $step = 1;
?>
        <br/><br/>
        <table class="contentpaneopen" style="border: solid 1px lightgrey;" cellpadding="5" cellspacing="0" border="0" width="100%">
        <tr style="background-color:#cccccc">
			<td class="contentheading" style="text-align:center" colspan="3"><?php echo _EA_MTG_TERMS;?></td>
		</tr>
		<tr valign="top" style="background-color:#eeeeee">
        	<td style="width:1%"><b><?php echo $step++; ?></b></td>
            <td style="width:25%"><?php echo _EA_MTG_INFO2a; ?></td>
			<td style="width:74%"><?php printf(_EA_MTG_INFO2b,$down_payment,$eaconf->ea_currency,$sale_price,$eaconf->ea_currency,$down_percent);?>
			</td>
        </tr>
        <tr valign="top" style="background-color:#fdfdfd">
        	<td><b><?php echo $step++; ?></b></td>
            <td><?php echo _EA_MTG_INFO3a;?></td>
			<td><?php printf(_EA_MTG_INFO3b, $annual_interest_rate, $annual_interest_percent);?></td>
        </tr>
        <tr valign="top" bgcolor="#cccccc">
        	<td colspan="3"><?php echo _EA_MTG_INFO4;?></td>
        </tr>
        <tr valign="top" style="background-color:#fdfdfd">
        	<td><b><?php echo $step++; ?></b></td>
            <td><?php echo _EA_MTG_INFO5a;?></td>
			<td><?php printf(_EA_MTG_INFO5b, $monthly_interest_rate, $annual_interest_rate);?></td>
        </tr>
        <tr valign="top" style="background-color:#eeeeee">
        	<td><b><?php echo $step++; ?></b></td>
            <td><?php echo _EA_MTG_INFO6a;?></td>
			<td><?php printf(_EA_MTG_INFO6b, $month_term, $year_term);?></td>
        </tr>
        <tr valign="top" style="background-color:fdfdfd">
        	<td><b><?php echo $step++; ?></b></td>
            <td><?php echo _EA_MTG_INFO7a;?></td>
			<td><?php echo _EA_MTG_INFO7b;?>
					<?php echo  $eahelper->valFormat($financing_price); ?> * (<?php echo  $eahelper->valFormat($monthly_interest_rate); ?> / (1 - ((1 + <?php echo  $eahelper->valFormat($monthly_interest_rate); ?>)<sup>-(<?php echo $month_term; ?>)</sup>)))
             		<?php echo _EA_MTG_INFO7c;?>
			</td>
        </tr>
        </table>
        <br/>

		<?php
        // Set some base variables
        $principal     = $financing_price;
        $current_month = 1;
        $current_year  = date("Y");
		// This basically, re-figures out the monthly payment, again.
        $power = -($month_term);
        $denom = pow((1 + $monthly_interest_rate), $power);
        $monthly_payment = $principal * ($monthly_interest_rate / (1 - $denom));
		
        print "<table style=\"width:100%; background-color:#f9f9f9; border: solid 1px lightgrey;\"cellpadding=\"5\" cellspacing=\"0\">";
		print "<tr style=\"background-color:#cccccc\"><td class=\"contentheading\" style=\"text-align:center\" colspan=\"4\">"._EA_MTG_AMORTIZATION." <b>". $eahelper->valFormat($monthly_payment)."</b>"._EA_MTG_OVER." ".$year_term." "._EA_MTG_YEARS."<br/></td></tr>";

        // This LEGEND will get reprinted every 12 months
        $legend1 = "\t<tr><th colspan=\"4\" style=\"background-color:#fff2aa\">"._EA_MTG_YEAR.$current_year."</th></tr>\n";
		$legend = "\t<tr valign=\"top\" style=\"background-color:#cccccc\">\n";
        $legend .= "\t\t<td style=\"text-align:right\">"._EA_MTG_MONTH."</td>\n";
        $legend .= "\t\t<td style=\"text-align:right\">"._EA_MTG_INTERESTPAID."</td>\n";
        $legend .= "\t\t<td style=\"text-align:right\">"._EA_MTG_PRINCIPALPAID."</td>\n";
        $legend .= "\t\t<td style=\"text-align:right\">"._EA_MTG_REMAININGBLNC."</td>\n";
        $legend .= "\t</tr>\n";
				
        echo $legend1;
		echo $legend;

        // Loop through and get the current month's payments for
        // the length of the loan
        
		while ($current_month <= $month_term) {
            $interest_paid     = $principal * $monthly_interest_rate;
            $principal_paid    = $monthly_payment - $interest_paid;
            $remaining_balance = $principal - $principal_paid;

            $this_year_interest_paid  = $this_year_interest_paid + $interest_paid;
            $this_year_principal_paid = $this_year_principal_paid + $principal_paid;
			
			print("\t<tr valign=\"top\" bgcolor=\"#eeeeee\">\n");
            print("\t\t<td style=\"text-align:right\">" . $current_month . "</td>\n");
            print("\t\t<td style=\"text-align:right\">" .  $eahelper->valFormat($interest_paid)  . "</td>\n");
            print("\t\t<td style=\"text-align:right\">" .  $eahelper->valFormat($principal_paid) . "</td>\n");
            print("\t\t<td style=\"text-align:right\">" .  $eahelper->valFormat($remaining_balance)  . "</td>\n");
            print("\t</tr>\n");

            ($current_month % 12) ? $show_legend = FALSE : $show_legend = TRUE;

            if ($show_legend) {
                print("\t<tr valign=\"top\" bgcolor=\"#ffffcc\">\n");
                print("\t\t<td colspan=\"4\">"._EA_MTG_TOTALS.$current_year . "</td>\n");
                print("\t</tr>\n");

                $total_spent_this_year = $this_year_interest_paid + $this_year_principal_paid;
                print("\t<tr valign=\"top\" style=\"background-color:#ffffcc\">\n");
                print("\t\t<td colspan=\"2\">&nbsp;</td>\n");
                print("\t\t<td colspan=\"2\">\n");
                print("\t\t\t"._EA_MTG_TOTALS1." <b>" .  $eahelper->valFormat($total_spent_this_year). "</b>"._EA_MTG_TOTALS2.$current_year . "<br/>\n");
                print("\t\t\t<b>" .  $eahelper->valFormat($this_year_interest_paid)  . "</b>"._EA_MTG_TOTALS3."<br/>\n");
                print("\t\t\t<b>" .  $eahelper->valFormat($this_year_principal_paid) . "</b>"._EA_MTG_TOTALS4."<br/>\n");
                print("\t\t</td>\n");
                print("\t</tr>\n");

                print("\t<tr valign=\"top\" style=\"background-color:#ffffff\">\n");
                print("\t\t<td colspan=\"4\" style=\"text-align:right\">&nbsp;<a href=\"#top\">"._EA_UP."</a><br/><br/></td>\n");
                print("\t</tr>\n");

                $current_year++;
                
				$this_year_interest_paid  = 0;
                $this_year_principal_paid = 0;

                if (($current_month + 6) < $month_term) {
                    echo "\t<tr><th colspan=\"4\" style=\"background-color:#fff2aa\">"._EA_MTG_YEAR.$current_year."</th></tr>\n";
					echo $legend;
                
				}
            }

            $principal = $remaining_balance;
            $current_month++;
        }
        print("</table>\n");
    }
?>



<?php
if ($form_complete) {
	print("<div align=\"center\"><input class=\"button\" type=\"button\" value=\""._EA_MTG_CLOSEWIN."\" onclick=\"javascript:window.close()\" /><br /><br /></div>");
}
 



?>
